import { Popconfirm, Button, Divider, Dropdown, Form, Icon, Menu, message ,Upload,Tooltip } from 'antd';
import React, {useRef, useState} from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { FormComponentProps } from 'antd/es/form';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable, {ActionType, ProColumns, UseFetchDataAction} from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import UpdateForm, { FormValueType } from './components/UpdateForm';
import { TableListItem } from './data.d';
import {  updateCourse, removeCourse ,queryCourse, addCourse } from './service';
import {ArrStringFun} from "@/utils/myUtils";
import XLSX from 'xlsx';
interface TableListProps extends FormComponentProps {}

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: FormValueType) => {
  const hide = message.loading('正在添加');
  try {
    console.log(fields);
    await addCourse({
      ...fields
    });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields) => {
  const hide = message.loading('正在修改');
  try {
    await updateCourse({
      ...fields
    });
    hide();
    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};

const TableList: React.FC<TableListProps> = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const actionRef = useRef<ActionType>();
  const columns: ProColumns<TableListItem>[] = [

    {
      title: '课程名称',
      dataIndex: 'course_name',
    },
    {
      title: '系部名称',
      dataIndex: 'department_name',
    },
    {
      title: '人数',
        dataIndex: 'people_num',
    },
    {
      title: '时间',
      dataIndex: 'time',
    },
    {
      title: '教室',
      dataIndex: 'classroom_name',
    },
    {
      title: '教师',
      dataIndex: 'teacher_name',
    },
    // {
    //   title: '教室id',
    //   dataIndex: 'classroom_id',
    // },{
    //   title: '系部id',
    //   dataIndex: 'department_id',
    // },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleUpdateModalVisible(true);
              setStepFormValues(record);
            }}
          >
            修改
          </a>
          <Divider type="vertical" />
          <Popconfirm
            title="您确定要删除吗？"
            icon={<Icon type="question-circle-o" style={{ color: 'red' }} />}
            onConfirm={async()=>{
              // handleRemove(record)
              const hide = message.loading('正在删除');
              try {
                let data = await removeCourse({
                  //key: selectedRows.map(row => row.key),
                  id: record.key
                });
                console.log(data)
                if(data.data == true){
                  actionRef.current.reload();
                  hide();
                  message.success('删除成功');
                }
                return true;
              } catch (error) {
                hide();
                message.error('删除失败，请重试');
                return false;
              }}}>
            <a href="#">删除</a>
          </Popconfirm>
        </>
      ),
    },
  ];

  const uploadprops = {
    // 这里我们只接受excel2007以后版本的文件，accept就是指定文件选择框的文件类型
    accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    name: 'file',
    headers: {
      authorization: 'authorization-text',
    },
    showUploadList: false,
    // 把excel的处理放在beforeUpload事件，否则要把文件上传到通过action指定的地址去后台处理
    // 这里我们没有指定action地址，因为没有传到后台
    beforeUpload: (file, fileList) => {
      var rABS = true;
      const f = fileList[0];
      var reader = new FileReader();
      reader.onload = function (e) {
        var data = e.target.result;
        if (!rABS) data = new Uint8Array(data);
        var workbook = XLSX.read(data, {
          type: rABS ? 'binary' : 'array'
        });
        // 假设我们的数据在第一个标签
        var first_worksheet = workbook.Sheets[workbook.SheetNames[0]];
        // XLSX自带了一个工具把导入的数据转成json
        var jsonArr = XLSX.utils.sheet_to_json(first_worksheet, {header:1});
        // 通过自定义的方法处理Json，比如加入state来展示
        jsonArr.slice(1).forEach(item=>{
          let data = {
            course_name:item[0],
            department_id:item[1],
            classroom_id:item[2],
            people_num:item[3],
            time:item[4],
            teacher_id:item[5],
          }
          handleAdd(data);
        })
        actionRef.current.reload();
      };
      if (rABS) reader.readAsBinaryString(f); else reader.readAsArrayBuffer(f);
      return false;
    }
  };
  return (
    <PageHeaderWrapper>
      <ProTable<TableListItem>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="key"
        toolBarRender={(action, { selectedRows }) => [
        <Button icon={<PlusOutlined />} type="primary" onClick={() => handleModalVisible(true)}>
          新建
        </Button>,
        <Upload {...uploadprops}>
          <Tooltip title='导入excel文件'>
            <Button  type="primary" >
              <Icon type="upload" /> 导入Excel
            </Button>
          </Tooltip>
        </Upload>,
        selectedRows && selectedRows.length > 0 && (
          <Dropdown
            overlay={
              <Menu
                onClick={async e => {
                  if (e.key === 'remove') {
                    const hide = message.loading('正在删除');
                    try {
                      let data = await removeCourse({
                        id:  ArrStringFun(selectedRows.map(row => row.key)),
                      });
                      console.log(data)
                      if(data.data == true){
                        actionRef.current.reload();
                        hide();
                        message.success('删除成功');
                      }
                      return true;
                    } catch (error) {
                      hide();
                      message.error('删除失败，请重试');
                      return false;
                    }}
                  }
                }
                selectedKeys={[]}
              >
                <Menu.Item key="remove">批量删除</Menu.Item>
              </Menu>
            }
          >
            <Button>
              批量操作 <Icon type="down" />
            </Button>
          </Dropdown>
        ),
      ]}
        renderTableAlert={(selectedRowKeys, selectedRows) => (
        <div>
          已选择 <a style={{ fontWeight: 600 }}>{selectedRowKeys.length}</a> 项&nbsp;&nbsp;
          <span>
              服务调用次数总计 {selectedRows.reduce((pre, item) => pre + item.callNo, 0)} 万
            </span>
        </div>
      )}
        request={params => queryCourse(params)}
        columns={columns}
        rowSelection={{}}
        />
        <CreateForm
          onSubmit={async value => {
            const success = await handleAdd(value);
            if (success) {
              handleModalVisible(false);
              actionRef.current.reload();
            }
          }}
          onCancel={() => handleModalVisible(false)}
          modalVisible={createModalVisible}
        />
        {stepFormValues && Object.keys(stepFormValues).length ? (
          <UpdateForm
            onSubmit={async value => {
              const success = await handleUpdate(value);
              if (success) {
                handleModalVisible(false);
                setStepFormValues({});
                actionRef.current.reload();
              }
            }}
            onCancel={() => {
              handleUpdateModalVisible(false);
              setStepFormValues({});
            }}
            updateModalVisible={updateModalVisible}
            values={stepFormValues}
          />
        ) : null}
    </PageHeaderWrapper>
  );
};

export default TableList;
